<script setup lang="ts">
import HandsonTable from 'handsontable'
import { registerAllModules } from 'handsontable/registry'
import 'handsontable/styles/handsontable.css'
import 'handsontable/styles/ht-theme-main.css'
// import 'handsontable/styles/ht-theme-horizon.css'
import '@/style/handsontable-theme.css'
import { registerLanguageDictionary, zhCN } from 'handsontable/i18n'
import { HyperFormula } from 'hyperformula'
import { REPORT_FORM_ID, REPORT_ID } from '@/enum/modules/report'
import type { LoadDataResponse } from './type'
import useTheme from '../useTheme'
import { HEADER_CELL_CLASS, READONLY_CELL_CLASS, ROUND_NUMBER as _ROUND_NUMBER } from '../config'
import useLoadReportDetail from './useLoadReportDetail'

defineOptions({ name: 'SummaryCompanyElectricity3' })

const props = defineProps<{
  time: string
}>()

// 电量电费汇总表精度保留到6位
const ROUND_NUMBER = _ROUND_NUMBER + 2

registerLanguageDictionary(zhCN)

// register Handsontable's modules
registerAllModules()

// 转供电
// eslint-disable-next-line
const reportId = REPORT_ID.ELECTRICITY_BILL_SUMMARY
const formId = REPORT_FORM_ID.ELECTRICITY_BILL_SUMMARY_3
// 当前企业名称
// const tenantName = ref('')
// 远程数据
const loadDataResponse = shallowRef<LoadDataResponse>()
const { res, loadReportData } = useLoadReportDetail()

const HEADES = [
  [
    '序号',
    '转供户名称',
    '电量（万kwh）',
    null,
    null,
    '电费（万元）',
    null,
    null,
    // '上月电价（元/kwh）',
    '本月电价（元/kwh）',
  ],
  [
    null,
    null,
    '本月',
    '上月累计',
    '本月累计',
    '本月',
    '上月累计',
    '本月累计',
    // null,
    null,
  ],
]

const wrapper = ref<HTMLElement>()
const hot = ref<HandsonTable>()

const newMergeCells = shallowRef<HandsonTable.GridSettings['mergeCells']>(
  [
    { row: 0, col: 0, rowspan: 2, colspan: 1 },
    { row: 0, col: 1, rowspan: 2, colspan: 1 },
    { row: 0, col: 2, rowspan: 1, colspan: 3 },
    { row: 0, col: 5, rowspan: 1, colspan: 3 },
    { row: 0, col: 8, rowspan: 2, colspan: 1 },
    // { row: 0, col: 9, rowspan: 2, colspan: 1 },
  ],
)

// 加载数据
async function loadData() {
  if (!props.time)
    return
  await loadReportData(props.time, unref(formId))
  const src = loadDataResponse.value = unref(res)

  const dataList = []
  // 插入公司总转供量所在行
  dataList.push([
    null,
    '公司总转供量',
    // 等待公式填充
    ...Array(7).fill(null),
  ])

  // 前面的4行
  const initial = 4
  let start = initial
  // 循环插入单位转供电数据
  const zgd = src?.zgd
  if (zgd && zgd.length) {
    for (let i = 0; i < zgd.length; i++) {
      const item = zgd[i]
      const array = []
      const end = start + item.dataList.length
      if (item.dataList.length || end > start) {
        array.push(
          i + 1,
          item.enterpriseName,
          `=ROUND(SUM(C${start + 1}:C${end}), ${ROUND_NUMBER})`,
          `=ROUND(SUM(D${start + 1}:D${end}), ${ROUND_NUMBER})`,
          // 电量本月累计
          `=ROUND(C${start}+D${start}, ${ROUND_NUMBER})`,
          `=ROUND(SUM(F${start + 1}:F${end}), ${ROUND_NUMBER})`,
          `=ROUND(SUM(G${start + 1}:G${end}), ${ROUND_NUMBER})`,
          // 电费本月累计
          `=ROUND(F${start}+G${start}, ${ROUND_NUMBER})`,
          // `=ROUND(SUM(I${start + 1}:I${end}), ${ROUND_NUMBER})`,
          // 本月电价
          `=IFERROR(ROUND(F${start}/C${start}, ${ROUND_NUMBER}), "")`,
        )
      }
      else {
        array.push(
          i + 1,
          item.enterpriseName,
          ...Array(7).fill(0),
        )
      }
      // 插入单位汇总行
      dataList.push(array)

      // 循环插入单位转供电数据
      for (let j = 0; j < item.dataList.length; j++) {
        const v = item.dataList[j]
        const array = []
        start++
        array.push(
          `(${j + 1})`,
          v.name,
          v.dl,
          v.dlLastMonthTotal,
          // 电量本月累计 = 上月累计 + 本月
          `=ROUND(C${start}+D${start},${ROUND_NUMBER})`,
          v.df,
          v.dfLastMonthTotal,
          // 电费本月累计 = 上月累计 + 本月
          `=ROUND(F${start}+G${start},${ROUND_NUMBER})`,
          // v.djLastMonth,
          // 单价-本月 = 本月电费 / 本月电量
          `=IFERROR(ROUND(F${start}/C${start},${ROUND_NUMBER}),"")`,
        )
        dataList.push(array)
      }

      // 跳过单位汇总行
      start++
    }
  }

  const data = [
    ...HEADES,
    ...dataList,
  ]

  // 填充公式
  if (data.length > HEADES.length) {
    const formulas = generateFormulas()
    for (const key in formulas) {
      const item = formulas[key as keyof typeof formulas]
      if (item.length) {
        for (const { row, col, exp } of item) {
          data[+row][+col] = exp
        }
      }
    }
  }
  hot.value?.loadData(data)
}

function updateSettings() {
  if (hot.value) {
    const s = hot.value.getSourceData()
    const rows = s.reduce((acc, cur: any, index) => {
      if (String(cur[0] || '').indexOf('(') === 0) {
        acc.push(index)
      }
      return acc
    }, [])
    hot.value.updateSettings({
      mergeCells: newMergeCells.value,
      cells: (row, col) => {
        if (row < HEADES.length) {
          return { className: `htCenter htMiddle ${HEADER_CELL_CLASS}` }
        }
        // B列除行号为1的外其他居左对齐
        if (col === 1 && row !== 0 && !rows.includes(row)) {
          return { className: 'htLeft' }
        }
        return {}
      },
    })
  }
}

// 生成公式
function generateFormulas() {
  const result = {
    // 公司总供电量所在行公式（行号为3）
    total: [] as { row: number | string, col: number | string, exp: string }[],
  }
  const src = loadDataResponse.value
  const zgd = src?.zgd ?? []
  if (zgd.length) {
    // 前面的4行
    const initial = 4
    let row = initial
    // 单位汇总行号集
    const rows: number[] = []
    for (const { dataList } of zgd) {
      rows.push(row)
      row += dataList.length + 1
    }
    // console.log('rows=', rows)
    const getExp = (colName: string) => {
      let exp = ''
      for (const r of rows) {
        exp += `${colName}${r}+`
      }
      return `=ROUND(${exp.slice(0, -1)},${ROUND_NUMBER})`
    }
    // 更新公司总供电量所在行公式（行号为3）
    result.total.push(...[
      [2, '2', getExp('C')],
      [2, '3', getExp('D')],
      [2, '4', getExp('E')],
      [2, '5', getExp('F')],
      [2, '6', getExp('G')],
      [2, '7', getExp('H')],
      // 电价-上月
      // [2, '8', null],
      // 电价-本月
      // [2, '9', `=IFERROR(ROUND(F3/C3, ${ROUND_NUMBER}), "")`],
      [2, '8', `=IFERROR(ROUND(F3/C3, ${ROUND_NUMBER}), "")`],
    ].map(([row, col, exp]) => ({ row, col, exp } as { row: number, col: string, exp: string })))
  }
  return result
}

function init() {
  if (!wrapper.value)
    return
  hot.value = new HandsonTable(wrapper.value, {
    fixedRowsTop: HEADES.length,
    selectionMode: 'single',
    readOnly: true,
    // disableVisualSelection: true,
    language: zhCN.languageCode,
    data: [...HEADES],
    formulas: {
      engine: HyperFormula,
    },
    className: 'htCenter htMiddle',
    readOnlyCellClassName: READONLY_CELL_CLASS,
    stretchH: 'all',
    // autoColumnSize: true,
    colWidths: (col) => {
      return col === 1 ? 150 : 100
    },
    manualColumnResize: true,
    colHeaders: true,
    rowHeaders: true,
    mergeCells: [],
    licenseKey: 'non-commercial-and-evaluation',
  })

  // debug
  if (import.meta.env.VITE_REPORT_DEBUG === '1') {
    hot.value.addHook('afterSelection', (row, col) => {
      if (row > -1 && col > -1) {
        console.info(`[${row},${col}] ${hot.value?.getSourceDataAtCell(row, col)}`)
        document.execCommand('copy')
      }
    })
  }
}

const { isDark } = useTheme(async () => {
  // 主题切换后，重新初始化实例
  if (hot.value) {
    hot.value.destroy()
    hot.value = undefined
    await bootstrap()
  }
})

async function bootstrap() {
  // 初始化实例
  init()
  // 加载数据和配置
  await loadData()
  updateSettings()
}

onMounted(bootstrap)
</script>

<template>
  <div class="h-full w-full">
    <div
      ref="wrapper" class="h-full w-full overflow-auto" :class="{
        'ht-theme-main-dark': isDark,
        'ht-theme-main': !isDark,
      }"
    />
  </div>
</template>
